package com.hyt.it.ogt.kq.main.controller.bm;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.util.DateUtils;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.exception.annotation.ThrowsAdvice;
import com.hyt.it.ogt.kq.common.bm.utils.Constant;
import com.hyt.it.ogt.kq.common.gov.config.swagger.ApiVersionConstant;
import com.hyt.it.ogt.kq.service.bm.model.vo.*;
import com.hyt.it.ogt.kq.service.bm.service.IInvoiceService;
import com.hyt.log.annotation.Log;
import com.hyt.loginfo.controller.BaseLoginController;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.util.UserIdToNameUtil;
import com.hyt.model.PageParam;
import com.hyt.swagger.ApiVersion;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 发票详细信息表 前端控制器
 * </p>
 *
 * @author liteng
 * @since 2020-08-28
 */
@RestController
@Api(tags = "15.发票详细信息", value = "发票详细信息")
@ApiSort(value = 15)
@RequestMapping("/bm/invoice")
@Slf4j
public class InvoiceController extends BaseLoginController {

    @Autowired
    private IInvoiceService iInvoiceService;

    @Autowired
    protected UserIdToNameUtil<InvoiceVo> userIdToNameUtil;

    @ApiOperation(value = "15.1.1  管理端：查询任务列表", notes = "14001:成功")
    @ApiOperationSort(value = 1)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object queryPage(InvoiceParam param, PageParam<InvoiceVo> pageParam) {
        IPage<InvoiceVo> page = pageParam;
        if (StringUtils.isNotBlank(param.getProjectState())) {
            param.setCurrentTime(DateUtils.getNowTime("yyyy-MM-dd HH:mm:ss"));
        }
        param.setOfficeId(getOfficeId());
        page = iInvoiceService.queryInvoiceProject(pageParam, param);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(page).build();
    }

    
    @ApiOperation(value = "15.1.2  管理端：开票管理", notes = "14001:成功, 31151201: 获取不到当前登录人信息", response = InvoiceVo.class)
    @ApiOperationSort(value = 2)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 31151202, print = "开票管理列表查询失败")
    @RequestMapping(value = "/invoicePage", method = RequestMethod.GET)
    public ApiResponse<IPage<InvoiceVo>> queryInvoicePage(InvoiceParam param) {
        log.info("invoicePage  param={}", JSON.toJSONString(param));
        param.setDeptIds(getDeptIds());

        User currUser = getSysUser();
        if (null == currUser || StringUtils.isEmpty(currUser.getId())) {
            return ApiResponse.<IPage<InvoiceVo>> builder().code(31151201).build();
        }

        IPage<InvoiceVo> page = iInvoiceService.queryInvoice(param);
        return ApiResponse.<IPage<InvoiceVo>> builder().code(Constant.RESPONSE_CODE_SUCCESS).data(page).build();
    }

    
    @ApiOperation(value = "15.1.3  管理端：开票管理导出", notes = "14001:成功")
    @ApiOperationSort(value = 3)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 31151301, print = "开票管理导出失败")
    @Log(module = "发票管理", business = "导出发票信息")
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(InvoiceParam param, HttpServletResponse response) {
        param.setDeptIds(getDeptIds());
        param.setSize(-1);
        iInvoiceService.export(param, response);
    }

    @ApiOperation(value = "15.1.4  管理端：查询订单开票申请列表", notes = "14001:成功, 31151401: 获取不到当前登录人信息")
    @ApiOperationSort(value = 4)
    @RequestMapping(value = "/applyPage", method = RequestMethod.GET)
    public Object applyPage(PageParam<InvoiceApplyVo> pageParam, InvoiceApplyParam param) {
        User currUser = getSysUser();
        if (null == currUser || StringUtils.isEmpty(currUser.getId())) {
            return ApiResponse.builder().code(31151401).data(null).build();
        }
        IPage<InvoiceApplyVo> page = pageParam;
        if (StringUtils.isBlank(param.getOfficeId())) {
            param.setOfficeId(getOfficeId());
        }
        page = iInvoiceService.queryApplyPage(pageParam, param);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(page).build();
    }

    @ApiOperation(value = "15.1.5  管理端：订单申请开票", notes = "14001:成功")
    @ApiOperationSort(value = 5)
    @Log(module = "发票详细信息管理", business = "订单申请开票")
    @RequestMapping(value = "/applyInvoice", method = RequestMethod.POST)
    public Object applyInvoice(@RequestBody
    InvoiceApply invoiceApply) {
        try {
            if (StringUtils.isEmpty(invoiceApply.getOfficeId())) {
                invoiceApply.setOfficeId(getOfficeId());
            }
            invoiceApply.setCreateBy(getUserId());
            String id = iInvoiceService.saveInvoiceApply(invoiceApply);
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(id).build();
        } catch (Exception ex) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010115).build();
        }
    }

    @ApiOperation(value = "15.1.6  管理端：确认开票", notes = "14001:成功")
    @ApiOperationSort(value = 6)
    @Log(module = "发票详细信息管理", business = "确认开票")
    @RequestMapping(value = "/applySave", method = RequestMethod.POST)
    public Object applySave(@RequestBody
    InvoiceCommonParam param) {
        try {
            // 获取当前登录人机构
            String officeId = getOfficeId();
            // 南昌保安员机构不支持开票
            if(StrUtil.isNotEmpty(officeId) && "ZA194324297538756608984212361754".equals(officeId)) {
                return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010116).build(); 
            }
            log.info("## applySave确认开票params：{}", FastJsonUtil.getBeanToJson(param));
            iInvoiceService.saveInvoice(param.getInvoiceIds());
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).build();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010116).build();
        }
    }

    @ApiOperation(value = "15.1.7  管理端：回调方法", notes = "14001:成功")
    @ApiOperationSort(value = 7)
    @Log(module = "发票详细信息管理", business = "回调方法")
    @RequestMapping(value = "/callBackForInvoice", method = RequestMethod.POST)
    public Object callBackForInvoice(HttpServletRequest req, HttpServletResponse resp, String invoiceId, @RequestBody InvoiceNotifyEvent invoiceNotifyEvent) {
        try {
            if (StringUtils.isEmpty(invoiceId)) {
                invoiceId = req.getParameter("invoiceId");
            }
            log.info("## callBackForInvoice invoiceId:{}, invoiceNotifyEvent:{} ", invoiceId, FastJsonUtil.getBeanToJson(invoiceNotifyEvent));
            Boolean result = iInvoiceService.callBackForInvoice(invoiceId, invoiceNotifyEvent);
            if (result) {
                return "SUCCESS";
            }
            return "FAIL";
        } catch (Exception ex) {
            log.error("## callBackForInvoice error", ex);
            return "FAIL";
        }
    }

    @ApiOperation(value = "15.1.8  管理端：退回", notes = "14001:成功")
    @ApiOperationSort(value = 8)
    @Log(module = "发票详细信息管理", business = "退回")
    @RequestMapping(value = "/saveBackForInvoice", method = RequestMethod.POST)
    public Object saveBackForInvoice(@RequestBody
    InvoiceBackParam invoiceBackParam) {
        try {
            iInvoiceService.saveBackForInvoice(invoiceBackParam.getInvoiceId());
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).build();
        } catch (Exception ex) {
            log.info("## saveBackForInvoice() error", ex);
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010116).build();
        }
    }
    
    @ApiOperation(value = "15.1.9  管理端：重置", notes = "20000:成功, 31151901:重置开票状态失败, 31151902:获取不到登录人信息, 31151903:重置发票参数不合法")
    @ApiOperationSort(value = 9)
    @Log(module = "发票详细信息管理", business = "重置开票状态")
    @RequestMapping(value = "/resetInvoiceStatus", method = RequestMethod.POST)
    public ApiResponse<Boolean> resetInvoiceStatus(@RequestBody InvoiceBackParam invoiceBackParam) {
        // 首先获取
        User user = getSysUser();
        if(null == user || StrUtil.isBlankIfStr(user.getId())) {
            return ApiResponse.<Boolean>builder().code(31151902).data(Boolean.FALSE).build();
        }
        
        // 校验参数
        if(null == invoiceBackParam || StrUtil.isBlankIfStr(invoiceBackParam.getInvoiceId())) {
            return ApiResponse.<Boolean>builder().code(31151903).data(Boolean.FALSE).build();
        }
        
        try {
            Boolean result = iInvoiceService.resetInvoiceStatus(user, invoiceBackParam.getInvoiceId());
            return ApiResponse.<Boolean>builder().code(20000).data(result).build();
        } catch (Exception ex) {
            log.info("## resetInvoiceStatus error", ex);
            return ApiResponse.<Boolean>builder().code(31151901).data(Boolean.FALSE).build();
        }
    }

    @ApiOperation(value = "15.2.1  管理端：查看团体信息", notes = "14001:成功")
    @ApiOperationSort(value = 21)
    @RequestMapping(value = "/queryOrderDetail", method = RequestMethod.GET)
    public Object queryOrderDetail(String invoiceId) {
        try {
            List<InvoiceApplyVo> list = iInvoiceService.queryOrderDetail(invoiceId);
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(list).build();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010117).build();
        }
    }
    
    
    
    

}
